# 导入flask以及相关子模块(安装方式：pip install flask)
#nohup /root/anaconda3/bin/python healthyDetectService.py >record.log 2>&1
import threading
import time
from flask import Flask, render_template, request
import os
import sys
import uuid
import json

from healthyDetect.configReaderUtils import configReaderUtils

curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
from yoloService.yosDispatcher import yosDispatcher
from healthyDetect.imgDetectThread import imgDetectThread
import torch

yos = yosDispatcher()

#读取参数
configReaderUtils.readConfig()
#加载模型
configReaderUtils.loadDetectModel(yos)

#启动http服务
app = Flask(__name__,static_folder=configReaderUtils.staticResource,static_url_path='/resources')


# 单张图片检测
@app.route('/hurtDetect', methods=['GET', 'POST'])
def hurtDetect():
    #-----------------------1.获取参数-----------------------
    imgData = request.files["detectedImages"]
    threshold=request.form.get('threshold')
    detetType=request.form.get('detetType')

    th = torch.tensor(float(threshold))

    #-----------------------2.处理保存图片-----------------------
    detectModel,device,half,imageSaveDir,ImgOutPath,imgPrefix=configReaderUtils.getDetctResrouce(detetType)
    # 获取图片名称及后缀名
    imgName = imgData.filename

    processImgName = str(uuid.uuid4()) + "." + imgName.split(".")[1]

    # 图片path和名称组成图片的保存路径
    file_path = imageSaveDir + processImgName

    # 保存图片
    imgData.save(file_path)

    #-----------------------3.根据检测类型分模型进行检测-----------------------

    #检测图片
    imgInformation = {
        "fileName": imgName,
        "detectType": detetType,
        "processImgName": processImgName,
        "savedPath": file_path,
        "outPath": ImgOutPath,
        "imgPrefix":imgPrefix
    }
    with torch.no_grad():
          result=yos.detect(model=detectModel,device=device,half=half,ImgPath=file_path,
                            outPath=ImgOutPath,conf_thres=th,imgInfoMap=imgInformation)
          return result


@app.route('/faceHurtDetect', methods=['GET', 'POST'])
def faceHurtDetect():
    t0 = time.time()
    # 通过表单中name值获取图片
    fileName = request.form.get("fileName")
    processImgName=request.form.get("processImgName")
    savedPath=request.form.get("savedPath")

    threshold=request.form.get('threshold')

    #获取资源
    detectModel,device,half,imageSaveDir,ImgOutPath,imgPrefix=configReaderUtils.getDetctResrouce(configReaderUtils.DETECT_TYPE_FACE)


    th = torch.tensor(float(threshold))

    imgInformation = {
        "fileName": fileName,
        "detectType": "face",
        "processImgName": processImgName,
        "savedPath": savedPath,
        "outPath": ImgOutPath,
        "imgPrefix": imgPrefix
    }

    detectResult=[]
    #检测图片
    with torch.no_grad():
          result=yos.detect(model=detectModel,device=device,half=half,ImgPath=savedPath,
                            outPath=ImgOutPath,conf_thres=th,imgInfoMap=imgInformation)
          return result


#多张图片同时检测
@app.route('/hurtDetectMultiImg', methods=['GET','POST'])
def hurtDetectMultiImg():
    t0 = time.time()
    # --------------------1.获取数据，整理数据--------------------
    detectImgs =request.files.getlist("detectImages")

    threshold=request.form.get('threshold')

    #解析图片，检测类型的关系
    detectTypeStr = request.form.get('detectTypeMap')
    detectTypeArray=json.loads(detectTypeStr)
    detectTypeMap={}
    for item in detectTypeArray:
        detectTypeMap[item['fileName']]=item['detectType']

    th = torch.tensor(float(threshold))

    # --------------------2.开启线程进行检测--------------------
    threadList=[]
    for imageItem in detectImgs:

        orignImgName = imageItem.filename
        #根据文件名获取检测类型
        detectType=detectTypeMap[orignImgName]
        processImgName=str(uuid.uuid4())+"."+orignImgName.split(".")[1]

        detectModel, device, half, imageSaveDir, ImgOutPath,imgPrefix = configReaderUtils.getDetctResrouce(configReaderUtils.DETECT_TYPE_FACE)

        savedPath=imageSaveDir + processImgName
        imgInformation={
            "fileName":orignImgName,
            "detectType":detectType,
            "processImgName":processImgName,
            "savedPath":savedPath,
            "outPath":ImgOutPath,
            "imgPrefix":imgPrefix
        }
        # 保存图片
        imageItem.save(savedPath)
        detectThread=imgDetectThread(model=detectModel,device=device,half=half,conf_thres=th,imgInfoMap=imgInformation)
        detectThread.start()
        threadList.append(detectThread)

    # --------------------3.获取检测结果并组装返回--------------------
    detectResult=[]
    for threadItem in threadList:
        threadItem.join()
        detectResult.append(threadItem.getDetectResult())

    resultData = {
        "requestCode":uuid.uuid4(),
        "detectTotalDuration": '%.3fS' % ( time.time()-t0),
        "detectionResult": detectResult
    }
    return resultData

app.run(host = configReaderUtils.hostAddr,port = configReaderUtils.port)
